<template>
  <div>
    <BasicModal @register="registerModal" width="600px" v-bind="$attrs" title="活动">
      <div class="container">
        <BasicForm class="m-10px" @register="registerForm">
          <template #comment="{ model, field }">
            <div class="flex">
              <Input
                v-model:value="model[field]"
                placeholder="请输入评论"
                @press-enter="handleSendComment"
              />
              <a-button :icon="h(SendOutlined)" @click="handleSendComment" />
            </div>
          </template>
        </BasicForm>
        <ScrollContainer class="h-200px">
          <div
            v-for="item in commentList"
            :key="item.id"
            class="comment-box"
            @mouseenter="handleMouseEnter(item)"
            @mouseleave="handleMouseLeave(item)"
          >
            <div v-if="item.author" class="comment-content">
              <div>
                <div class="flex w-400px">
                  <p class="comment-author">{{ item.author }}</p>
                  <p class="comment-text">{{ item.time }}</p>
                </div>
                <p class="comment-text">{{ item.text }}</p>
              </div>
              <div
                v-show="item.show"
                :key="item.id"
                class="action-buttons"
                :class="{ 'show-buttons': item.show }"
              >
                <!-- <a-button type="text" :icon="h(EditOutlined)" @click="handleEdit(item)" /> -->
                <a-button type="text" :icon="h(DeleteOutlined)" @click="handleDelete(item)" />
              </div>
            </div>
            <div v-else class="comment-text">{{ item.text }} &nbsp;&nbsp;{{ item.time }}</div>
          </div>
        </ScrollContainer>
      </div>
      <template #footer>
        <a-button key="back" @click="handleAck" v-show="!acknowledged">应答</a-button>
        <a-button key="back" @click="handleClear" v-show="!cleared">清除</a-button>
      </template>
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { ref, h } from 'vue';
  import { SendOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { Input } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { schemas, userInfo } from './CommentModal.data';
  import { getAlarmComment, sendComment, ackAlarm, clearAlarm } from '/@/api/thingsborad/alarm';
  import { ScrollContainer } from '/@/components/Container';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { deleteComment } from '/@/api/thingsborad/alarm';
  import dayjs from 'dayjs';
  import relativeTime from 'dayjs/plugin/relativeTime';
  import jwt_decode from 'jwt-decode';

  dayjs.extend(relativeTime);
  dayjs.locale('zh-cn');
  const { createConfirm } = useMessage();
  const commentList = ref<Array<any>>([]);
  const alarmId = ref<string>('');
  const acknowledged = ref<boolean>(false);
  const cleared = ref<boolean>(false);
  const [registerForm, { resetFields, getFieldsValue }] = useForm({
    layout: 'vertical',
    labelWidth: 200,
    size: 'large',
    schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const [registerModal, { setModalProps }] = useModalInner(async (data) => {
    setModalProps({
      confirmLoading: true,
      okText: '清除',
      cancelText: '应答',
      canFullscreen: false,
    });
    alarmId.value = data.alarmId;
    acknowledged.value = data.acknowledged;
    cleared.value = data.cleared;
    initComment(alarmId.value);
    setModalProps({ confirmLoading: false });
  });
  // 发送按钮
  function handleSendComment() {
    const { comment } = getFieldsValue();
    if (!comment) return;
    saveComment(comment);
  }
  // 保存评论
  async function saveComment(text: string) {
    if (!text) return;
    let params = {
      alarmId: {
        entityType: 'ALARM',
        id: alarmId.value,
      },
      comment: {
        text: text,
      },
      type: 'OTHER',
    };
    await sendComment(params);
    initComment(alarmId.value);
    resetFields();
  }
  // 删除评论
  async function handleDelete(item: any) {
    createConfirm({
      iconType: 'info',
      title: '你想删除这条评论吗？',
      content: item.text,
      onOk: async () => {
        await deleteComment({
          alarmId: item.alarmId,
          commentId: item.id,
        });
        initComment(alarmId.value);
      },
    });
  }
  // 应答
  async function handleAck() {
    await ackAlarm(alarmId.value);
    initComment(alarmId.value);
    acknowledged.value = true;
  }
  // 清除
  async function handleClear() {
    await clearAlarm(alarmId.value);
    initComment(alarmId.value);
    cleared.value = true;
  }
  // 鼠标移入
  function handleMouseEnter(item) {
    const token = localStorage.getItem('jwt_token') || '';
    const userInfo: userInfo = jwt_decode(token);
    if (userInfo.userId == item.authorId) {
      item.show = true;
    }
  }
  // 鼠标移出
  function handleMouseLeave(item) {
    item.show = false;
  }
  // 评论初始化
  async function initComment(alarmId) {
    commentList.value = [];
    let params = {
      pagination: {
        page: 0,
        pageSize: 2147483647,
        sortProperty: 'createdTime',
        sortOrder: 'DESC',
      },
      alarmId: alarmId,
    };
    const alarmComment = await getAlarmComment(params);
    alarmComment.data.forEach((item: any) => {
      let text = JSON.parse(item.name).text;
      commentList.value.push({
        id: item.id.id,
        authorId: item?.userId?.id,
        alarmId: item?.alarmId?.id,
        show: false,
        text: text,
        time: dayjs(item.createdTime).fromNow(),
        author:
          item.type == 'OTHER'
            ? item.firstName && item.lastName
              ? item.firstName + ' ' + item.lastName
              : item.email
            : null,
      });
    });
  }
</script>

<style lang="less" scoped>
  p {
    margin: 0;
  }
  .container {
    border: 1px solid rgb(48 86 128);
    border-radius: 5px;
    padding: 20px;
  }
  .comment-box {
    margin-bottom: 15px;
    padding: 10px;
    border-radius: 10px;
    &:hover {
      background-color: #b0b4cf33;
    }
  }
  .comment-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .comment-author {
    white-space: nowrap;
    font-size: 16px;
    color: #000000c2;
    font-weight: 500;
    letter-spacing: 0.25px;
    margin-right: 10px;
    text-align: start;
    line-height: 19px;
  }
  .comment-text {
    font-weight: 500;
    width: 350px;
    font-size: 14px;
    letter-spacing: 0.25px;
    color: #00000061;
  }
  .action-buttons {
    visibility: hidden;
  }
  .show-buttons {
    display: flex;
    visibility: visible;
  }
</style>
